package com.dzl.userwx.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.pojo.WelfareGoodsModifyRecord;
import com.dzl.goods.service.WelfareGoodsModifyRecordService;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.integral.pojo.WelfareIntegralGrantDetail;
import com.dzl.integral.service.WelfareIntegralGrantDetailService;
import com.dzl.userwx.dao.WelfareUserPurchasesNumMapper;
import com.dzl.userwx.pojo.WelfareUserPurchasesNum;
import com.dzl.userwx.pojo.vo.WelfareUserPurchasesNumVo;
import com.dzl.userwx.service.WelfareUserPurchasesNumService;
import com.dzl.util.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 用户虚拟商品购买次数信息表(welfare_user_purchases_num)表服务实现类
 * @author liuguanjun
 * @date 2021-11-13 09:59:17
 */
@Service
public class WelfareUserPurchasesNumServiceImpl extends BaseServiceImpl<WelfareUserPurchasesNum> implements WelfareUserPurchasesNumService {

    @Autowired
    private WelfareUserPurchasesNumMapper mapper;
    @Autowired
    private WelfareGoodsService welfareGoodsService;
    @Autowired
    private WelfareIntegralGrantDetailService welfareIntegralGrantDetailService;
    @Autowired
    private WelfareGoodsModifyRecordService welfareGoodsModifyRecordService;

    @Override
    public Integer updatePurchasesNumByUserIds(List<Integer> userIds) {
        //根据用户id查询用户商品购买次数
        List<WelfareUserPurchasesNumVo> list = mapper.selectGoodsPurchasesNumByUserIds(userIds);
        if (EmptyUtils.isNotEmpty(list)) {
            list.forEach(welfareUserPurchasesNumVo -> {
                //更新用户商品购买次数
                WelfareUserPurchasesNum welfareUserPurchasesNum = new WelfareUserPurchasesNum();
                welfareUserPurchasesNum.setId(welfareUserPurchasesNumVo.getId());
                welfareUserPurchasesNum.setSurplusPurchasesNum(welfareUserPurchasesNumVo.getSurplusPurchasesNum()+welfareUserPurchasesNumVo.getBuyLimit());
                welfareUserPurchasesNum.setUpdateTime(new Date());
                mapper.updateByPrimaryKeySelective(welfareUserPurchasesNum);
            });
            return list.size();
        }
        return 0;
    }

    @Override
    public Integer getUserSurplusPurchasesNumByUserIdAndGoodsId(Integer userId,Integer goodsId) {
        //查询用户此商品可购买次数
        WelfareUserPurchasesNum query = new WelfareUserPurchasesNum();
        query.setUserId(userId);
        query.setGoodsId(goodsId);
        List<WelfareUserPurchasesNum> list = mapper.select(query);
        //若WelfareUserPurchasesNum记录存在，则取该条记录的surplusPurchasesNum值
        if(EmptyUtils.isNotEmpty(list)){
            WelfareUserPurchasesNum welfareUserPurchasesNum = list.get(0);
            return welfareUserPurchasesNum.getSurplusPurchasesNum();
        }else{
            //若WelfareUserPurchasesNum记录不存在，则取商品的buyLimit值
            WelfareGoods welfareGoods = welfareGoodsService.selectByPrimaryKey(goodsId);
            if(EmptyUtils.isNotEmpty(welfareGoods) && EmptyUtils.isNotEmpty(welfareGoods.getBuyLimit()) && welfareGoods.getBuyLimit()>0
                    && EmptyUtils.isNotEmpty(welfareGoods.getBuyLimitType()) && welfareGoods.getBuyLimitType().equals(2)){
                return welfareGoods.getBuyLimit();
            }
            return 99999;
        }
    }

    @Override
    public Integer updateUserPurchasesNum(Integer userId,Integer goodsId,Integer buyNum) {
        //查询用户此商品可购买次数
        WelfareUserPurchasesNum query = new WelfareUserPurchasesNum();
        query.setUserId(userId);
        query.setGoodsId(goodsId);
        List<WelfareUserPurchasesNum> list = mapper.select(query);
        //若WelfareUserPurchasesNum记录存在，则修改该条记录的surplusPurchasesNum值和usedPurchasesNum值
        if(EmptyUtils.isNotEmpty(list)){
            WelfareUserPurchasesNum welfareUserPurchasesNum = list.get(0);
            welfareUserPurchasesNum.setUsedPurchasesNum(welfareUserPurchasesNum.getUsedPurchasesNum()+buyNum);
            welfareUserPurchasesNum.setSurplusPurchasesNum(welfareUserPurchasesNum.getSurplusPurchasesNum()-buyNum);
            welfareUserPurchasesNum.setUpdateTime(new Date());
            return mapper.updateByPrimaryKeySelective(welfareUserPurchasesNum);
        }else{
            //若WelfareUserPurchasesNum记录不存在，则创建
            WelfareGoods welfareGoods = welfareGoodsService.selectByPrimaryKey(goodsId);
            if(EmptyUtils.isNotEmpty(welfareGoods) && EmptyUtils.isNotEmpty(welfareGoods.getBuyLimit()) && welfareGoods.getBuyLimit()>0
              && EmptyUtils.isNotEmpty(welfareGoods.getBuyLimitType()) && welfareGoods.getBuyLimitType().equals(2)){
                WelfareUserPurchasesNum welfareUserPurchasesNum = new WelfareUserPurchasesNum();
                welfareUserPurchasesNum.setGoodsId(goodsId);
                welfareUserPurchasesNum.setUserId(userId);
                WelfareIntegralGrantDetail WelfareIntegralGrantDetailSelect = new WelfareIntegralGrantDetail();
                WelfareIntegralGrantDetailSelect.setUserId(userId);
                List<WelfareIntegralGrantDetail> integralGrantDetailList = welfareIntegralGrantDetailService.select(WelfareIntegralGrantDetailSelect);
                WelfareGoodsModifyRecord welfareGoodsModifyRecordSelect = new WelfareGoodsModifyRecord();
                welfareGoodsModifyRecordSelect.setGoodsId(goodsId);
                List<WelfareGoodsModifyRecord> goodsModifyRecordList = welfareGoodsModifyRecordService.select(welfareGoodsModifyRecordSelect);
                if (EmptyUtils.isNotEmpty(goodsModifyRecordList) && goodsModifyRecordList.size() > 0){
                    Integer buyLimit = getPurchasesNumFromModify(integralGrantDetailList,goodsModifyRecordList);
                    if (buyLimit -buyNum > 0) {
                        welfareUserPurchasesNum.setSurplusPurchasesNum(buyLimit -buyNum);
                    } else {
                        welfareUserPurchasesNum.setSurplusPurchasesNum(0);
                    }
                } else {
                    welfareUserPurchasesNum.setSurplusPurchasesNum(welfareGoods.getBuyLimit() * integralGrantDetailList.size() -buyNum);
                }
                welfareUserPurchasesNum.setUsedPurchasesNum(buyNum);
                welfareUserPurchasesNum.setCreateTime(new Date());
                welfareUserPurchasesNum.setUpdateTime(new Date());
                return mapper.insertSelective(welfareUserPurchasesNum);
            }
            return 0;
        }
    }

    /**
     * 根据分发和商品修改记录计算用户的购买限制次数
     * @author ChenLong
     * @date 2021-11-15 14:25:01
     * @param integralGrantDetailList 分发记录列表
     * @param goodsModifyRecordList 商品修改记录
     * @return java.lang.Integer
     **/
    private Integer getPurchasesNumFromModify(List<WelfareIntegralGrantDetail> integralGrantDetailList,List<WelfareGoodsModifyRecord> goodsModifyRecordList){
        integralGrantDetailList.sort(Comparator.comparing(WelfareIntegralGrantDetail::getCreateTime));
        goodsModifyRecordList.sort(Comparator.comparing(WelfareGoodsModifyRecord::getCreateTime));
        Integer buyLimit = 0;
        for (int i=0;i<integralGrantDetailList.size();i++){
            WelfareIntegralGrantDetail welfareIntegralGrantDetailTemp = integralGrantDetailList.get(i);
            for (int j=0;j<goodsModifyRecordList.size();j++){
                // 如果不是最后一条
                if (j==0){
                    if (welfareIntegralGrantDetailTemp.getCreateTime().compareTo(goodsModifyRecordList.get(j).getCreateTime()) < 0){
                        buyLimit = buyLimit + goodsModifyRecordList.get(j).getBuyLimitOld();
                    } else {
                        buyLimit = buyLimit + goodsModifyRecordList.get(j).getBuyLimit();
                    }
                } else if(j==goodsModifyRecordList.size()-1){
                    if (welfareIntegralGrantDetailTemp.getCreateTime().compareTo(goodsModifyRecordList.get(j).getCreateTime()) < 0){
                        buyLimit = buyLimit + goodsModifyRecordList.get(j-1).getBuyLimit();
                    } else {
                        buyLimit = buyLimit + goodsModifyRecordList.get(j).getBuyLimit();
                    }
                } else {
                    // 分发时间早于修改时间
                    if (welfareIntegralGrantDetailTemp.getCreateTime().compareTo(goodsModifyRecordList.get(j).getCreateTime()) < 0
                            && welfareIntegralGrantDetailTemp.getCreateTime().compareTo(goodsModifyRecordList.get(j+1).getCreateTime()) > 0){
                        buyLimit = buyLimit + goodsModifyRecordList.get(j).getBuyLimit();
                    }
                }
            }
        }
        return buyLimit;
    }
}
